PeControl = function (opt) {
    this.baseurl = 'http://localhost:8080/ci/';
    this.ctrlopt = {};
    this.hide=function(){
        $("#" + opt.name).hide();
    }

    this.show = function () {
        $("#" + opt.name).show();
    }    
    
    this.control =$("#" + opt.name);
    
    return this;//$("#" + opt.name);
}


FgControl = function (opt) {
    var ctrl = new PeControl(opt);

    ctrl.grid = function () { console.log('grid') };

    ctrl.class = function (cls) { ctrl.control.addClass(cls) };

    ctrl.hide = function () {console.log('hide aja') };
    return ctrl;
}


GrdInptControl = function (opt) {
    var ctrl = new PeControl(opt);

    return ctrl;
}
//PeControl.prototype.kkk = function () { console.log('kkkk')}

GrdControl = function (opt) {   


    var ctrl = new PeControl(opt);

    var startrendergrid = function (grid, rslt) {
        var stmp = "";
        var actbutton = function (gr, rsltrw) {
            var txx = '';
            if (gr.actioncol != undefined) {
                txx = '<td class=" ">';
                $.each(gr.actioncol, function (k, v) {
                    if (v.type == "edit")
                        txx += '<a class="btn btn-xs blue act-edit' + (v.hide != undefined || false ? ' hide' : '') + '"><i class="fa fa-pencil"></i> </a>';
                    else if (v.type == "delete")
                        txx += '<a class="btn btn-xs red act-delete' + (v.hide != undefined || false ? ' hide' : '') + '"><i class="fa fa-trash-o"></i> </a>';
                    else if (v.type == "save")
                        txx += '<a class="btn btn-xs purple act-save' + (v.hide != undefined || false ? ' hide' : '') + '"><i class="fa fa-save"></i> </a>';
                    else if (v.type == "cancel")
                        txx += '<a class="btn btn-xs yellow act-cancel' + (v.hide != undefined || false ? ' hide' : '') + '"><i class="fa fa-undo"></i> </a>';
                    else if (v.type == "view")
                        txx += '<a class="btn btn-xs green act-view' + (v.hide != undefined || false ? ' hide' : '') + '"><i class="fa fa-search"></i> </a>';
                });
                txx += '<input type="hidden" value="' + (rsltrw != undefined ? rsltrw[grid.key] : '') + '">';
                + '</td>';
            }
            return txx;
        };


        var gencb = function (data, gr) {
            if (gr.checkbox) {
                return '<td>'
                  + '<input id="cb_' + data[gr.key] + '" type="checkbox" class="checkboxes" />'
               + '</td>';
            }

        };

        var genrow = function (irw, gr) {
            var ttx = '';
            ttx += '<tr id="tr_' + irw + '" class="' + (irw % 2 != 1 ? 'odd' : 'even') + '">';

            $.each(gr.columns, function (k, v) {
                if (v.control != undefined) {
                    v.control.name = v.mData + '_' + irw;
                }

                ttx += '<td class=" ">'
                    + '</td>';
            });

            ttx += actbutton(gr);
            ttx += '\n</tr>';

            return ttx;
        }


        var tbl = $("#" + grid.name + ' thead tr').empty();
        var rw = $("#" + grid.name + ' tbody').empty();
        //header
        if (grid.checkbox) {
            stmp = '<th class="table-checkbox">'
                 + '<input type="checkbox" class="group-checkable" data-set="#' + grid.name + ' .checkboxes"/>'
                 + '</th>';
            tbl.append(stmp);
        }

        $.each(grid.columns, function (k, v) {
            stmp = '\n<th style="' + (v.colwidth != undefined ? 'width:' + v.colwidth : '') + '">'
                    + '\n' + v.sTitle
                    + '\n</th>';
            tbl.append(stmp);
        });

        if (grid.actioncol != undefined) {
            stmp = '<th style="width:81px;" >'
            + 'Action'
            + '</th>';
            tbl.append(stmp);
        }

        //row
        stmp = '';
        if (rslt != undefined) {
            $.each(rslt, function (k, v) {
                stmp += '\n<tr>';
                stmp += gencb(v, grid);
                $.each(grid.columns, function (key, value) {
                    stmp += '<td>' + (value.mRender == undefined ? v[value.mData] : value.mRender(v[value.mData])) + '</td>';
                });
                //action button
                stmp += actbutton(grid, v);
                stmp += '\n</tr>';

            });
        }
        else {

            for (var i = 0; i < grid.initrow; i++) {

                stmp += genrow(i, grid);
            }
        }

        //console.log(stmp);
        rw.append(stmp);
        //tbl = $("#" + grid.name + ' thead tr').empty();
        if (!grid.datatable) {
            var btn = $('#btn_' + grid.name + '_additem');
            btn.show();
            $(btn).on('click', function () {
                $("#" + grid.name + " tbody").append(genrow($("#" + grid.name + " tbody tr").length, grid));
                $('#' + grid.name + ' .btn-xs').unbind('click');
                gridbehave(grid);
            });
        }
        return true;
    }

    var renderdatatablegrid = function (grid) {
        var stmp = "";
        if (grid.isinit) {
            startrendergrid(grid);
        }
        else {
            $.ajax({
                type: "POST",
                url: ctrl.baseurl + grid.url,
                dataType: 'json',
                data: grid.params,
                async: false,
                success: function (rslt) {
                    startrendergrid(grid, rslt);
                }
            });
        }
        //return false;
    }

    var gridbehave = function (gr) {
        $('#' + gr.name + " .act-edit").on('click', function () {
            var tr = $(this).closest('tr');
            editrow(tr, gr);
            $('.act-save,.act-cancel', tr).removeClass('hide');
            $('.act-edit,.act-delete,.act-view', tr).addClass('hide');
        });

        $('#' + gr.name + " .act-cancel").on('click', function () {
            var tr = $(this).closest('tr');
            restorerow(tr, gr);
            $('.act-edit,.act-delete,.act-view', tr).removeClass('hide');
            $('.act-save,.act-cancel', tr).addClass('hide');

            var rwid = $('td:last', tr).find('input').val();
            if (rwid == '') {
                $('td:not(:last)', tr).each(function () {
                    $(this).html('');
                });
            }
            else {
                //restorerow(tr,gr);
                self.submit(baseurl + gr.url + '/' + $("#KdPo").val() + '/' + rwid, {}, true, function (rslt) { gr.oncancel(tr, rslt); });

            }
        });
    }

    //ctrl.ctrlopt = opt.gridopt;
    ctrl.gridopt = opt.gridopt;

    ctrl.control = {
        toolbar: $('#' + opt.name + '_toolbar'),
        table: $('#' + opt.name + '_wrapper')
    }
    ctrl.hide = function () {
        $('#' + opt.name + '_toolbar').hide();
         $('#' + opt.name + '_wrapper').hide();
    }

    ctrl.show = function () {
        $('#' + opt.name + '_toolbar').show();
         $('#' + opt.name + '_wrapper').show();
    }

    
    ctrl.reload = function () {
        var grid = ctrl.gridopt;
        var stmp = "";

        if ($("#" + grid.name + "_filter").length > 0) {
            var oTable = $('#' + grid.name).dataTable();
            oTable.fnDestroy();
        }
        else {
            $("#" + grid.name + " tbody").empty();
        }

        var isserverside = grid.serverside == undefined ? false : grid.serverside;
        renderdatatablegrid(grid);

        if (grid.datatable == undefined || grid.datatable) {
            if (!isserverside) {
                var gridopt = {
                    aLengthMenu: [
                        [5, 15, 20, -1],
                        [5, 15, 20, "All"] // change per page values here
                    ],
                    bLengthChange: (grid.hideshowrecord == undefined ? true : !grid.hideshowrecord),
                    // set the initial value
                    sDom: "<'row'<'col-md-6 col-sm-12'f><'col-md-6 col-sm-12'l>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
                    iDisplayLength: 5,
                    sPaginationType: "bootstrap",
                    bDestroy: true,
                    callback: grid.ondone,
                    aoColumnDefs: [
                        { bSortable: false, aTargets: [0] }
                    ],
                    bFilter: grid.filter == undefined ? false : grid.filter,
                    oLanguage: {
                        sLengthMenu: "_MENU_ records",
                        oPaginate: {
                            sPrevious: "Prev",
                            sNext: "Next"
                        }
                    },
                    fnDrawCallback: function (e) {
                        if (grid.rwdblclick != undefined) {
                            $("#" + grid.name + " tbody tr").dblclick(function (e) {
                                var data = oTable.fnGetData(this);
                                grid.rwdblclick(data);
                            });
                        }
                        if (grid.ondone != undefined) {
                            grid.ondone();
                        }

                    }
                }
            }
            else {
                var gridopt = {
                    aLengthMenu: [
        [5, 15, 20, -1],
        [5, 15, 20, "All"] // change per page values here
                    ],
                    // set the initial value
                    sDom: "<'row'<'col-md-6 col-sm-12'f><'col-md-6 col-sm-12'l>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
                    iDisplayLength: 5,
                    sPaginationType: "bootstrap",
                    sServerMethod: "POST",
                    sAjaxSource: this.getbaseurl() + grid.url,
                    bDestroy: true,
                    bRetrieve: true,
                    bServerSide: true,
                    aoColumns: grid.columns,
                    bFilter: grid.filter == undefined ? false : grid.filter,
                    oLanguage: {
                        sLengthMenu: "_MENU_ records",
                        oPaginate: {
                            sPrevious: "Prev",
                            sNext: "Next"
                        }
                    },
                    fnDrawCallback: function (e) {
                        if (grid.rwdblclick != undefined) {
                            $("#" + grid.name + " tbody tr").dblclick(function (e) {
                                var data = oTable.fnGetData(this);
                                grid.rwdblclick(data);
                            });
                        }

                        if (grid.ondone != undefined) {
                            grid.ondone();
                        }
                    }
                }
            }

            oTable = $("#" + grid.name).dataTable(gridopt);


            if (grid.checkbox) {
                if (isserverside) {
                    if ($("#gridrole thead tr th:first input").length == 0) {
                        $("#" + grid.name + " thead tr th:first").append('<input type="checkbox" class="group-checkable" data-set="#' + grid.name + ' .checkboxes"/>');
                    }
                }


                jQuery('#' + grid.name + ' .group-checkable').change(function () {
                    var set = jQuery(this).attr("data-set");
                    var checked = jQuery(this).is(":checked");
                    jQuery(set).each(function () {
                        if (checked) {
                            $(this).attr("checked", true);
                        } else {
                            $(this).attr("checked", false);
                        }
                    });
                    jQuery.uniform.update(set);
                });
            }

            jQuery('#' + grid.name + '_wrapper .dataTables_filter input').addClass("form-control input-large  input-inline"); // modify table search input
            jQuery('#' + grid.name + '_wrapper .dataTables_length select').addClass("form-control input-xsmall"); // modify table per page dropdown

            jQuery('#' + grid.name + '_wrapper .dataTables_filter').css('float', 'left');
            jQuery('#' + grid.name + '_wrapper .dataTables_length').css('float', 'right');
            //jQuery('#' + grid.name + '_wrapper .dataTables_length select').select2(); // initialize select2 dropdown


        }
        else {


            if (grid.editonhover) {
                $('#' + grid.name + " tbody tr").hover(
                    function () {
                        editrow(this, grid);
                    },
                    function () {
                        restorerow(this, grid);
                    }
                    );
            } else {
                gridbehave(grid)

            }
        }
    }
   

    return ctrl;

}

PageEngine = function (opt) {
    "use strict";
    /*variable*/
    var self = this;
    var shtml = "";
    var breadcrumb = "";
    //var baseurl = 'http://localhost:5073/';
    var baseurl = 'http://localhost:8080/ci/';
    var defaulticon = 'dot-circle-o';
    var btnevent = []; // { "1": "sdf" };// new Array();
    var validation = [];
    var form = '';
    var mustvalid = [];
    var lstswitch = [];
    var lang = "Bhs";

    var ctrlopt = {} ;
    var ctrfg = 0;

    
   



    /*get set*/
    this.getbaseurl = function () {
        return baseurl;
    }

    /*region private*/
    var privatefnc = function () {

        console.log('its private');
    }

    var inittoastr = function () {
        toastr.options = {
            "closeButton": true,
            "debug": false,
            "positionClass": "toast-bottom-full-width",
            "onclick": null,
            "showDuration": "1000",
            "hideDuration": "1000",
            "timeOut": "3000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }
    }


    this.clearcontrol = function (sid) {
        var pnl = $(sid + " input,"+sid +" select,"+sid+" textarea");
        $.each(pnl, function (k, v) {
            $(v).val('');
            $(v).closest('.form-group').removeClass('has-error')
        });

        var validator = $("#frm_"+sid.replace('#','')).validate();
        validator.resetForm();

    }

    this.showmessage = function (msg) {
        /*v.type:
        success
        info
        warning
        error */
        $.each(msg, function (k, v) {
            toastr[v.type](v.msg, v.title);
        });
    }

    this.Confirm = function (cnfrm) {
        var mdl = $('#staticmodal');
        if (cnfrm.title)
            $("#staticmodal h4").html(cnfrm.title);
        if(cnfrm.msg)
            $("#staticmodal .modal-body").html(cnfrm.msg);
        if (cnfrm.ok) 
            $("#btnstaticmodalok").on('click',  cnfrm.ok);     
        $('#staticmodal').modal();
    };


    this.showdebug = function (msg) {
        var stmp = '';

        $.each(msg, function (k, v) {
            stmp = '<div id="bootstrap_alerts_demo">'
	+ '<div id="" class="app-alerts alert alert-success fade in">'
	+ '<button class="close" aria-hidden="true" data-dismiss="alert" type="button"></button>'
	+ v

        + '</div>'
        + '</div>'
        });
        var html = $(".page-content");

        html.append(stmp);

    }


    this.readonly = function (opt) {
        /*
        opt.name = selection method
        opt.readonly= bool;
        */
        if (Object.prototype.toString.call(opt) === '[object Array]') {
            $.each(opt, function (k, v) {
                if (v.readonly || v.readonly == undefined) {
                    $(v.name).attr("readonly", "");
                }
                else {
                    $(v.name).removeAttr("readonly");
                }
            });
        }
        else {
            if (opt.readonly || opt.readonly == undefined) {
                //console.log('asfdd' + opt.name);
                $(opt.name).attr("readonly", "");
            }
            else {
                $(opt.name).removeAttr("readonly");
            }
        }
    }

    
    var startrendergrid = function (grid, rslt) {
        var stmp = "";
        var actbutton = function (gr,rsltrw) {
            var txx = '';
            if (gr.actioncol != undefined) {
                txx = '<td class=" ">';
                $.each(gr.actioncol, function (k, v) {
                    if (v.type == "edit")
                        txx += '<a class="btn btn-xs blue act-edit' + (v.hide != undefined || false ? ' hide' : '') + '"><i class="fa fa-pencil"></i> </a>';
                    else if (v.type == "delete")
                        txx += '<a class="btn btn-xs red act-delete' + (v.hide != undefined || false ? ' hide' : '') + '"><i class="fa fa-trash-o"></i> </a>';
                    else if (v.type == "save")
                        txx += '<a class="btn btn-xs purple act-save' + (v.hide != undefined || false ? ' hide' : '') + '"><i class="fa fa-save"></i> </a>';
                    else if (v.type == "cancel")
                        txx += '<a class="btn btn-xs yellow act-cancel' + (v.hide != undefined || false ? ' hide' : '') + '"><i class="fa fa-undo"></i> </a>';
                    else if (v.type == "view")
                        txx += '<a class="btn btn-xs green act-view' + (v.hide != undefined || false ? ' hide' : '') + '"><i class="fa fa-search"></i> </a>';
                });
                txx += '<input type="hidden" value="' + (rsltrw!=undefined?rsltrw[grid.key]:'') + '">';
                + '</td>';
            }
            return txx;
        };


        var gencb = function (data, gr) {
            if (gr.checkbox) {
                return '<td>'
                  + '<input id="cb_' + data[gr.key] + '" type="checkbox" class="checkboxes" />'
               + '</td>';
            }

        };

        var genrow = function (irw,gr) {
            var ttx = '';
            ttx += '<tr id="tr_' + irw + '" class="' + (irw % 2 != 1 ? 'odd' : 'even') + '">';

            $.each(gr.columns, function (k, v) {
                if (v.control != undefined) {
                    v.control.name = v.mData + '_' + irw;
                }

                ttx += '<td class=" ">'
                    + '</td>';
            });

            ttx += actbutton(gr);
            ttx += '\n</tr>';

            return ttx;
        }


        var tbl = $("#" + grid.name + ' thead tr').empty();
        var rw = $("#" + grid.name + ' tbody').empty();
        //header
        if (grid.checkbox) {
            stmp = '<th class="table-checkbox">'
                 + '<input type="checkbox" class="group-checkable" data-set="#' + grid.name + ' .checkboxes"/>'
                 + '</th>';
            tbl.append(stmp);
        }

        $.each(grid.columns, function (k, v) {
            stmp = '\n<th style="'+(v.colwidth!=undefined?'width:'+v.colwidth:'')+'">'
                    + '\n' + v.sTitle
                    + '\n</th>';
            tbl.append(stmp);
        });

        if (grid.actioncol != undefined) {
            stmp = '<th style="width:81px;" >'
            + 'Action'
            + '</th>';
            tbl.append(stmp);
        }

        //row
        stmp = '';
        if (rslt != undefined) {
            $.each(rslt, function (k, v) {
                stmp += '\n<tr>';
                stmp += gencb(v, grid);
                $.each(grid.columns, function (key, value) {
                    stmp += '<td>' + (value.mRender == undefined ? v[value.mData] : value.mRender(v[value.mData])) + '</td>';
                });
                //action button
                stmp +=actbutton(grid,v);
                stmp += '\n</tr>';

            });
        }
        else {
            
            for (var i = 0; i < grid.initrow; i++) {
                
                stmp+= genrow(i, grid);
            }
        }

        //console.log(stmp);
        rw.append(stmp);
        //tbl = $("#" + grid.name + ' thead tr').empty();
        if (!grid.datatable) {
            var btn = $('#btn_' + grid.name + '_additem');
            btn.show();
            $(btn).on('click', function () {                
                $("#" + grid.name + " tbody").append(genrow($("#" + grid.name + " tbody tr").length, grid));
                $('#' + grid.name + ' .btn-xs').unbind('click');
                gridbehave(grid);
            });
        }
        return true;
    }

    
    var gridbehave=function(gr)
    {

        $('#' + gr.name + " .act-edit").on('click', function () {            
            var tr = $(this).closest('tr');
            editrow(tr,gr);
            $('.act-save,.act-cancel', tr).removeClass('hide');                        
            $('.act-edit,.act-delete,.act-view', tr).addClass('hide');
        });

        $('#' + gr.name + " .act-cancel").on('click', function () {
            var tr = $(this).closest('tr');
            restorerow(tr,gr);
            $('.act-edit,.act-delete,.act-view', tr).removeClass('hide');
            $('.act-save,.act-cancel', tr).addClass('hide');
                       
            var rwid=$('td:last', tr).find('input').val();
            if (rwid == '') {
                $('td:not(:last)', tr).each(function () {
                    $(this).html('');
                });
            }
            else {
                //restorerow(tr,gr);
                self.submit(baseurl + gr.url +'/'+$("#KdPo").val()+ '/' + rwid, {}, true, function (rslt) { gr.oncancel(tr, rslt); });
                            
            }
        });
    }

    var editrow = function (rw,gr) {
        var jtd = $("td:not(:last)", rw);
        for (var i = 0; i < jtd.length; i++) {
            if (gr.columns[i].control != undefined) {
                var ctrl = (gr.columns[i].control.type == 'txt' ? renderinputtext(gr.columns[i].control) :
                           (gr.columns[i].control.type == "lkp" ? renderlookupinputbutton(gr.columns[i].control) : 'undefined'))

                if (gr.columns[i].control.type != "lkp") {
                    jtd[i].innerHTML = $(ctrl).attr('value', jtd[i].innerHTML).prop('outerHTML');;
                }
                else {
                    var c = $(ctrl);
                    $(c).find('input').attr('value', jtd[i].innerHTML);
                    jtd[i].innerHTML = $(c).prop('outerHTML');
                }

                if (gr.columns[i].control.type == "lkp") {
                    var cb = gr.columns[i].control.callback;
                    $('a', jtd[i]).on('click', function () { cb(rw); });
                }
            }
        }
    };

    var restorerow = function (rw,gr) {
        var jtdd = $("td:not(:last)", rw);
        //var inpt = $("input", this);
        for (var i = 0; i < jtdd.length  ; i++) {
            if (gr.columns[i].control != undefined) {
                var inpt = $(jtdd[i]).find('input');
                if (inpt.length > 0) {
                    jtdd[i].innerHTML = inpt[0].value;
                }
            }
        }
    };

    this.restorerowgrid = function (gr) {
        $.each($("#" + gr.name + " tbody tr"), function (k, v) {
            restorerow(v, gr);
        });
    }

        var renderdatatablegrid = function (grid) {
            var stmp = "";
            if(grid.isinit)
            {
                startrendergrid(grid);            
            }
            else{
                $.ajax({
                    type: "POST",
                    url: baseurl + grid.url,
                    dataType: 'json',
                    data: grid.params,
                    async: false,
                    success: function (rslt) {
                        startrendergrid(grid, rslt);
                    }
                });
            }
            //return false;
        }

        this.reloadgrid = function (grid) {
            var stmp = "";
            if ($("#" + grid.name + "_filter").length > 0) {
                var oTable = $('#' + grid.name).dataTable();
                oTable.fnDestroy();
            }
            else {
                $("#" + grid.name + " tbody").empty();
            }

            var isserverside = grid.serverside == undefined ? false : grid.serverside;
            renderdatatablegrid(grid);
        
            if (grid.datatable == undefined || grid.datatable) {
                if (!isserverside) {
                    var gridopt = {
                        aLengthMenu: [
                            [5, 15, 20, -1],
                            [5, 15, 20, "All"] // change per page values here
                        ],
                        bLengthChange: (grid.hideshowrecord == undefined ? true : !grid.hideshowrecord),
                        // set the initial value
                        sDom: "<'row'<'col-md-6 col-sm-12'f><'col-md-6 col-sm-12'l>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
                        iDisplayLength: 5,
                        sPaginationType: "bootstrap",
                        bDestroy: true,
                        callback: grid.ondone,
                        aoColumnDefs: [
                            { bSortable: false, aTargets: [0] }                            
                        ],
                        bFilter: grid.filter == undefined ? false : grid.filter,
                        oLanguage: {
                            sLengthMenu: "_MENU_ records",
                            oPaginate: {
                                sPrevious: "Prev",
                                sNext: "Next"
                            }
                        },
                        fnDrawCallback: function (e) {
                            if (grid.rwdblclick != undefined) {
                                $("#" + grid.name + " tbody tr").dblclick(function (e) {
                                    var data = oTable.fnGetData(this);
                                    grid.rwdblclick(data);
                                });
                            }
                            if (grid.ondone != undefined) {
                                grid.ondone();
                            }

                        }
                    }
                }
                else {
                    var gridopt = {
                        aLengthMenu: [
            [5, 15, 20, -1],
            [5, 15, 20, "All"] // change per page values here
                        ],
                        // set the initial value
                        sDom: "<'row'<'col-md-6 col-sm-12'f><'col-md-6 col-sm-12'l>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
                        iDisplayLength: 5,
                        sPaginationType: "bootstrap",
                        sServerMethod: "POST",
                        sAjaxSource: this.getbaseurl() + grid.url,
                        bDestroy: true,
                        bRetrieve: true,
                        bServerSide: true,
                        aoColumns: grid.columns,
                        bFilter: grid.filter == undefined ? false : grid.filter,
                        oLanguage: {
                            sLengthMenu: "_MENU_ records",
                            oPaginate: {
                                sPrevious: "Prev",
                                sNext: "Next"
                            }
                        },
                        fnDrawCallback: function (e) {
                            if (grid.rwdblclick != undefined) {
                                $("#" + grid.name + " tbody tr").dblclick(function (e) {
                                    var data = oTable.fnGetData(this);
                                    grid.rwdblclick(data);
                                });
                            }

                            if (grid.ondone != undefined) {
                                grid.ondone();
                            }
                        }
                    }
                }

                oTable = $("#" + grid.name).dataTable(gridopt);


                if (grid.checkbox) {
                    if (isserverside) {
                        if ($("#gridrole thead tr th:first input").length == 0) {
                            $("#" + grid.name + " thead tr th:first").append('<input type="checkbox" class="group-checkable" data-set="#' + grid.name + ' .checkboxes"/>');
                        }
                    }


                    jQuery('#' + grid.name + ' .group-checkable').change(function () {
                        var set = jQuery(this).attr("data-set");
                        var checked = jQuery(this).is(":checked");
                        jQuery(set).each(function () {
                            if (checked) {
                                $(this).attr("checked", true);
                            } else {
                                $(this).attr("checked", false);
                            }
                        });
                        jQuery.uniform.update(set);
                    });
                }

                jQuery('#' + grid.name + '_wrapper .dataTables_filter input').addClass("form-control input-large  input-inline"); // modify table search input
                jQuery('#' + grid.name + '_wrapper .dataTables_length select').addClass("form-control input-xsmall"); // modify table per page dropdown

                jQuery('#' + grid.name + '_wrapper .dataTables_filter').css('float', 'left');
                jQuery('#' + grid.name + '_wrapper .dataTables_length').css('float', 'right');
                //jQuery('#' + grid.name + '_wrapper .dataTables_length select').select2(); // initialize select2 dropdown


            }
            else {           


                if (grid.editonhover) {
                    $('#' + grid.name + " tbody tr").hover(
                        function () {
                            editrow(this,grid);
                        },
                        function () {
                            restorerow(this,grid);
                        }
                        );
                } else {
                    gridbehave(grid)
                   
                }
            }
        }

        this.hidealltoolbarbutton = function () {
            $('.breadcrumb .btn').addClass('hide');
        }

        this.showbuttontoolbar = function (sid) {
            this.hidealltoolbarbutton();
            var b = sid.indexOf(',') > 0 ? $(sid) : $("#" + sid);
            b.removeClass('hide');
        };

        this.hideallportlet = function () {
            var p = $(".portlet").addClass('hide');
        }

        this.showonlyportlet = function (sid) {
            this.hideallportlet();
            var p = sid.indexOf(',') > 0 ? $(sid) : $("#" + sid);
            p.removeClass('hide');
        }

        this.submit = function (uri, params, issync, callback) {
            var rslt = '';
            $.ajax({
                type: "POST",
                url: uri,
                data: params,
                dataType: 'json',
                traditional: true,
                async: !(issync == undefined ? true : issync),
                success: function (result) {
                    rslt = result;
                    if (callback && typeof (callback) === "function") {
                        callback(result);
                    }
                }
            });
            return rslt; //rslt;
        }


        this.render = function (callback) {
            
            shtml = "";

            var isexpr = this.submit(this.getbaseurl() + 'api/admin/apiuser/passexpires', false, true);

            if (isexpr == true) {
                rendercontrol([
                {
                    type: "row",
                    controls: [
                       { type: "changepassword" }
                    ]
                }
                ]);
            }
            else {
                rendercontrol(opt.controls);
            }

            var html = $(".page-content");
            html.append(shtml);


            if (breadcrumb != '')
                renderbreadcrumb(breadcrumb);

            /* init */
            //if (opt.cekpassexpired == undefined || !opt.cekpassexpired)            
            //  loadnav();
            //else


            if (isexpr == false || isexpr == undefined)
                loadnav();
            else {
                $("#sysbtnchangepassword").on('click', function () {
                    if (self.isvalid()) {
                        var data = $("#frmsyschangepassword").serializeObject();
                        var rslt = self.submit(self.getbaseurl() + 'scp/admin/user/changepassword', data, true);
                        if (rslt.success) {
                            window.location.href = "";
                        }
                        else {
                            console.log(rslt);
                            self.showmessage([{ type: "error", msg: rslt.message, title: "error edit"}]);
                        }
                    }
                });
            }
        

            $.each(btnevent, function (k, v) {
                $(v.name).on('click', v.cb);
            });


            this.fgsatu =  FgControl({
                type: "formgroup",
                name: 'fgsatu',
                controls: [
                       { name: "fltrKdPo", type: "textbox", label: "No. Po", cls: "col-md-3", placeholder: "Kode Barang" }

                ]
            });

            this.gridsupplier = GrdControl(ctrlopt.gridsupplier);
            this.gridpodtl = GrdControl(ctrlopt.gridpodtl);
            
            //this.fgsatu.prototype.kkk = function () { console.log('kkkk') }

            inittoastr();
            this.validinit();
            this.behave();
            $(".make-switch").bootstrapSwitch();

            if (callback && typeof (callback) === "function" && isexpr != true) {
                callback();
            }

        
        
        }

    
        this.isvalid = function () {
            //console.log(form);
            //form.element("#KdBrg2");
            var vldf = form.valid();
            var vld = true;
            //$.each(("#KdBrg1,#KdBrg2").split(','), function (k, v) {
            //    console.log(v);
            //    if (!form.validate().element(v)) {
            //        vld = false;
            //        console.log('retfalse');
            //        return false;
            //    }
            //});

            return vldf  && vld;
        
            //return false;//form.valid();
            //form.element("#KdBrg2");//,#KdBrg1");
            //return false
            //if (form.valid() == false) {
            //    return false;
            //}
            //else {
            //    return true;
            //}
        }

        this.behave = function () {
            $('#staticmodal').on('hidden.bs.modal', function () {
                $("#btnstaticmodalok").unbind('click');            
            });

            $("#Province.mstarea").on("change", function () {
                if ($(this).val() != '') {
                    self.PopulateCombo({ uri: 'api/APIcom/comboarea/k/' + $(this).val(), name: "City" });
                    $("#SubDistrict option:not(:first)").remove()
                }
            });

            $("#City.mstarea").on("change", function () {
                if ($(this).val() != '') {
                    self.PopulateCombo({ uri: 'api/APIcom/comboarea/c/' + $(this).val(), name: "SubDistrict" })
                }
            });

            $(".numeric").keydown(function (e) {
                // Allow: backspace, delete, tab, escape, enter and F5
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 116]) !== -1 ||
                    // Allow: Ctrl+A
                    (e.keyCode == 65 && e.ctrlKey === true) ||
                    // Allow: home, end, left, right
                    (e.keyCode >= 35 && e.keyCode <= 39)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
            });
            $(".decimal").keydown(function (e) {
                // Allow: backspace, delete, tab, escape, enter, F5 and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 116, 190]) !== -1 ||
                    // Allow: Ctrl+A
                    (e.keyCode == 65 && e.ctrlKey === true) ||
                    // Allow: home, end, left, right
                    (e.keyCode >= 35 && e.keyCode <= 39)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
            });

            $(".UCase").on('blur', function () {
                $(this).each(function () {
                    $(this).val($(this).val().toUpperCase())
                });
            });
            $(".LCase").on('blur', function () {
                $(this).each(function () {
                    $(this).val($(this).val().toLowerCase())
                });
            });
            $(".TCase").on('blur', function () {
                $(this).each(function () {
                    $(this).val($(this).val().replace(/(?:^|\s)\w/g, function (match) {
                        return match.toUpperCase();
                    }));
                });
            });
        }
        this.validinit = function () {

            form = $('#frmsyschangepassword'+mustvalid);
            //form = $('#frm_pnlInput');

            //var error = $('.alert-danger', form);
            //var success = $('.alert-success', form);

            /* custom validator */
            $.validator.addMethod("mustyanu", function (value, element) {
                return value === 'yanu';
            }, "harus yanu");        

            //form = $('#frmsyschangepassword' + mustvalid).validate({
            form.validate({        
                ignore: "",//"#KdBrg1,#KdBrg2", //validating hidden input
                doNotHideMessage:  true, //this option enables to show the error/success messages on tab switch.
                errorElement: 'span', //default input error message container
                errorClass: 'help-block', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                //groups:
                //    {
                //        namegroup:"KdBrg1 KdBrg2"
                //    },    
                //rules: {
                //    uname: {
                //        minlength: 5,
                //        required: true
                //    },
                //},
                //rules: {
                //    KdBrg1: "required",
                //    KdBrg2: "required"
                
                //},
                errorPlacement: function (error, element) {
                    if ($(element).parent().hasClass("multicntrl")) {
                        $(error).addClass("has-error");
                        $(element).parent().append(error);
                    }
                    else {
                        $(element).parent().append(error);
                    }
                },

                invalidHandler: function (event, validator) { //display error alert on form submit   
                    //success.hide();
                    //error.show();
                    //App.scrollTo(error, -200);    

                    //console.log(event);
                    //console.log(validator);
                    //$(validator.invalid).each(function (k, v) {
                    //    console.log("#" + v);
                    
                    ////});
                    //var lg =("KdBrg1 KdBrg2").split(' ');
                    //$.each(lg, function (k,v) {
                    //    console.log(v);
                    //    if (validator.invalid[v] != undefined) {
                    //        console.log('ksjdhfkjhsfdjkh');
                    //        $("#" + v).closest('.form-group').removeClass('has-success').addClass('has-error'); // set error class to the control group
                    //    }
                    //});


                    self.showmessage([{ type: "error", msg: "You have some form errors. Please check", title: "Error"}]);
                },

           

                unhighlight: function (element) { // revert the change done by hightlight
                    var prnt = $(element).parent();
                    if ($(prnt).hasClass("multicntrl")) {
                        $(element).removeClass("has-error").addClass("has-success");
                   

                    }
                    else {
                        //console.log('unhighlight success');
                        $(element)
                            .closest('.form-group').removeClass('has-error'); // set error class to the control group
                    }
                },
                highlight: function (element) { // hightlight error inputs
                    var prnt = $(element).parent();
                    if ($(prnt).hasClass("multicntrl")) {
                        $(element).removeClass("has-success").addClass("has-error");
                        //if ($(prnt).find(".has-error").length > 0) {
                        $(prnt).parent().find("label:first").removeClass('has-success').addClass('has-error');
                        //}

                    }
                    else {              
                        //console.log('error');
                        $(element)
                            .closest('.form-group').removeClass('has-success').addClass('has-error'); // set error class to the control group
                    }
                },            
                success: function (label) {
                    // display success icon for other inputs

                    label
                    .addClass('valid'); // mark the current input as valid and display OK icon
                    //.removeClass('has-error');
                    var prnt = $(label).parent();
                    //console.log($(prnt).find(".has-error"));
                    if ($(prnt).find(".has-error:not(.help-block)").length == 0) {
                        $(prnt).parent().find("label:first").removeClass('has-error').addClass('has-success');
                    }
                    //.closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group

                },
                submitHandler: function (form) {
                    //success.show();
                    //error.hide();
                    //add here some ajax code to submit your form or just call form.submit() if you want to submit the form without ajax
                }
            });

            //form.element("#KdBrg1,#KdBrg2");

        }

    
    
        var rendercontrol = function (ctrl) {

            $.each(ctrl, function (key, val) {

                var typ = val.type || 'textbox';
            

                switch (typ) {
                    case "modal":
                        rendermodal(val)
                        break;
                    case "row":
                        //console.log('render row');
                        renderrow(val);
                        break;
                    case "header":
                        //console.log('render header');
                        renderheadernav(val);
                        break;
                    case "btn":
                        //console.log('render button');
                        renderbutton(val);
                        break;
                    case "portlet":
                        //console.log('render portlet');
                        renderportlet(val);
                        break;
                    case "formgroup":
                        //console.log('render formgroup');
                        renderformgroup(val);
                        break;
                    case "textarea":
                        rendertextarea(val)
                        break;
                    case "textbox":
                        //console.log('render textbox');
                        rendertextbox(val);
                        break;
                    case "multiinput":
                        rendermultiinput(val);
                        break;
                    case "inputtextbox":
                        renderinputtextbox(val);
                        break;
                    case "switch":
                        renderswitch(val);
                        break;
                    case "formgroupbtn":
                        //console.log('render formgroupbtn');
                        renderformgroupbutton(val);
                        break;
                    case "gridtable":
                        //console.log('render grid');
                        rendergrid(val);
                        break;
                    case "btndropdown":
                        //console.log('render button dropdown');
                        renderbtndropdown(val);
                        break;
                    case "dropdownlist":
                        renderdropdown(val);
                        break;
                    case "dropdownlistonly":
                        renderdropdownonly(val);
                        break;
                    case "datetimepicker":
                        renderdatepicker(val);
                        break
                    case "daterange":
                        renderdaterange(val);
                        break;
                    case "h3":
                        renderhhh(val);
                        break;
                    case "lefttab":
                        renderlefttab(val);
                        break;
                    case "lookup":
                        renderlookup(val);
                        break;
                    case "hidden":
                        renderhidden(val)
                        break;
                    case "text":
                        rendertext(val);
                        break;
                    case "changepassword":
                        renderchangepassword(val)
                        break;
                    default:
                        break;
                }
            });
        }

        var renderchangepassword = function (chg) {
            shtml += '<form id="frmsyschangepassword" action="#">'
                                                        + '<div class="form-group">'
                                                            + '<label class="control-label">Current Password</label>'
                                                            + '<input required="true" name="hKLjhkljhgkGuhjVHGfdtrdyf" type="password" class="form-control"/>'
                                                        + '</div>'
                                                        + '<div class="form-group">'
                                                            + '<label class="control-label">New Password</label>'
                                                            + '<input required="true" id="KJytgWwqUJGfHBvUgfnjHg" name="KJytgWwqUJGfHBvUgfnjHg"  type="password" class="form-control"/>'
                                                        + '</div>'
                                                        + '<div class="form-group">'
                                                            + '<label class="control-label">Re-type New Password</label>'
                                                            + '<input required="true" equalTo="#KJytgWwqUJGfHBvUgfnjHg" id="LKJJHgfNKNbgufjnbkjg" name="LKJJHgfNKNbgufjnbkjg" type="password" class="form-control"/>'
                                                        + '</div>'
                                                        + '<div class="margin-top-10">'
                                                            + '<a href="#" id="sysbtnchangepassword" class="btn green">'
                                                                + ' Change Password'
                                                            + '</a>'
                                                        + '</div>'
                                                    + '</form>';


        }


        var renderhidden = function (hdn) {
            shtml += '<input id="' + hdn.name + '" type="button" value="Click me">';
        }

        var rendermodal = function (mdl) {
            shtml += '<div class="modal fade bs-modal-lg" id="' + mdl.name + '" tabindex="-1" role="dialog" aria-hidden="true">'
                                    + '<div class="modal-dialog modal-lg">'
                                        + '<div class="modal-content">'
                                            + '<div class="modal-header">'
                                                + '<button type="button" class="close" data-dismiss="modal"  ></button>'
            //+ '<h4 class="modal-title">Modal Title</h4>'
                                            + '</div>'
                                            + '<div class="modal-body">';

            rendercontrol(mdl.body);
            shtml += '</div>'
                  + '<div class="modal-footer">'
                      + '<button id="btnClose_' + mdl.name + '"type="button" class="btn red" data-dismiss="modal"><i class="fa fa-power-off"></i> Close</button>'
            //+ '<button type="button" class="btn blue">Save changes</button>'
                  + '</div>'
              + '</div>'
          + '</div>'
      + '</div>';
        }

        var renderlefttab = function (ltb) {
            shtml += '\n<div class="row">'
                  + '\n<div class="col-md-3">'
                                            + '\n<ul class="ver-inline-menu tabbable margin-bottom-10">';

            var iactive = ltb.active || 1;

            var i = 0;
            $.each(ltb.tabitem, function (k, v) {
                i++;
                shtml += '\n<li ' + (i == iactive ? 'class="active"' : '') + '>'
                                                    + '\n<a data-toggle="tab" href="#' + ltb.name + '-' + i + '">'
                                                        + '\n<i class="fa fa-' + v.icon + '"></i> ' + v.text
                                                    + '\n</a>'
                                                    + (i == 1 ? '\n<span class="after">\n</span>' : '')
                                                + '\n</li>';
            });

            shtml += '\n</ul>'
                  + '\n</div>'
                   + '<div class="col-md-9">'
                    + '<div class="tab-content">';
            i = 0;

            $.each(ltb.tabcontent, function (k, v) {
                i++;
                shtml += '\n<div id="' + ltb.name + '-' + i + '" class="tab-pane ' + (i == iactive ? 'active' : '') + '">';
                rendercontrol(v.controls)
                shtml += '\n</div>';
            });


            shtml += '\n</div>'
                 + '\n</div>';
            +'\n</div>';



        }
        var rendermenu = function (mnlist) {
            var html = "";
            $.each(mnlist, function (idx, val) {
                if (val !== null) {
                    var uri = val.menuurl == null ? "javascript:;" : self.getbaseurl() + val.menuurl;
                    var sicon = val.menuicon == null ? "arrow-circle-right" : val.menuicon;
                    if (val.childs !== undefined && val.childs.length > 0) {
                        html += "<li id='li_" + val.menuid + "'><a href=" + uri + " id=\"menu" + val.menuid + "\"><i class=\"fa fa-" + sicon + "\"></i>" +
                        "<span class=\"title\">" + val.menucaption + "</span><span class=\"arrow \"></span></a>";
                        html += "<ul class=\"sub-menu\">" + rendermenu(val.childs) + "</ul></li>";
                    }
                    else {
                        html += "<li id='li_" + val.menuid + "'><a href=" + uri + " id=\"menu" + val.menuid + "\"><i class=\"fa fa-" + sicon + "\"></i>" +
                        "<span class=\"title\">" + val.menucaption + "</span></a></li>";
                    }
                }
            });
            return html;
        }

        var loadnav = function () {
            $.ajax({
                type: "POST",
                url: baseurl + "api/admin/apilayout/loadnav",
                dataType: 'json',
                success: function (mnlist) {
                    $("#leftsidemenu").empty();
                    var deflt = "<li class=\"sidebar-toggler-wrapper\"><div class=\"sidebar-toggler hidden-phone\"></div></li><li class=\"sidebar-search-wrapper\"><form class=\"sidebar-search\" action=\"extra_search.html\" method=\"POST\"><div class=\"form-container\"><div class=\"input-box\"><a href=\"javascript:;\" class=\"remove\"></a><input type=\"text\" placeholder=\"Search...\"/><input type=\"button\" class=\"submit\" value=\" \"/></div></div></form></li><li class=\"start \"><a href=\"index.html\"><i class=\"fa fa-home\"></i><span class=\"title\">Dashboard</span></a></li>";
                    $("#leftsidemenu").append(deflt + rendermenu(mnlist));


                    $('#leftsidemenu a').on('click', function () {
                        var curmenu = ($.cookie('isudgfishdjkhgu') == undefined ? [] : $.cookie('isudgfishdjkhgu').split(","));
                        var indx = 0;

                        if ($("#li_" + $(this).attr('id').substring(4)).hasClass("open")) {
                            $.each($("#li_" + $(this).attr('id').substring(4) + " > ul.sub-menu li.open"), function (k, v) {
                                indx = curmenu.indexOf($(v).attr('id'));
                                curmenu.splice(indx, 1);
                            });
                            indx = curmenu.indexOf($("#li_" + $(this).attr('id').substring(4)));
                            curmenu.splice(indx, 1);
                        }
                        else {
                            console.log('open menu');
                            curmenu = [];
                            $.each($('#leftsidemenu li.open'), function (k, v) {
                                curmenu.push($(v).attr('id'));
                            });

                            if ($("#li_" + $(this).attr('id').substring(4) + " > ul").length > 0)
                                curmenu.push("li_" + $(this).attr('id').substring(4));
                        }
                        $.cookie('isudgfishdjkhgu', curmenu);
                    });

                    if ($.cookie('isudgfishdjkhgu') != undefined) {
                        var mn = $.cookie('isudgfishdjkhgu').split(",");
                        $.each($.cookie('isudgfishdjkhgu').split(","), function (k, v) {
                            if (v != '') {
                                $("#" + v + " > ul.sub-menu").show();
                                $("#" + v).addClass('open');
                            }
                        });
                    }


                }
            });
        }

        var renderbreadcrumb = function (menuid) {
            $.ajax({
                dataType: 'json',
                type: "POST",
                traditional: true,
                //async: false,
                url: baseurl + 'api/admin/apilayout/getbreadcrumbdata/' + breadcrumb,
                //"data":  { 'menuid': data['RcApplicationId'] },,
                success: function (result) {
                    var strbread = '';
                    $.each(result, function (key, val) {
                        strbread +=
                          '<li>'
                         + '<i class="fa fa-' + (val.menuicon === null ? defaulticon : val.menuicon) + '"></i>'
                         + '<a href="' + baseurl + val.menuurl + '">'
                         + val.menucaption
                         + '</a>'
                         + '<i class="fa fa-angle-right"></i>'
                         + '</li>';
                    });
                    $(".breadcrumb").append(strbread);
                }
            });

        }

        var renderbutton = function (val) {
            var ss = "";
            shtml += '\n<a href="#" id="' + val.name + '" class="btn ' + val.cls + ' ' + (val.size === undefined ? '' : val.size) + ' ' + val.color + '">'
                             + val.text + '\n<i class="fa fa-' + val.icon + '"></i>'
                             + '</a>';

            if (val.onClick != undefined && val.onclick != '') {
                var sid = "#" + val.name;
                btnevent.push({ name: sid, cb: val.onClick });
            }
        }
        var renderheadernav = function (ctrl) {

            if (ctrl.title != 'undefined' || ctrl.breadcrumb != 'undefined' || ctrl.toolbarbutton != 'undefined') {

                if (ctrl.title != 'undefined')
                    shtml += '<h3 class="page-title">'
                        + ctrl.title
                        + '</h3>';
                if (ctrl.breadcrumb != 'undefined' || ctrl.toolbarbutton != 'undefined') {
                    breadcrumb = ctrl.breadcrumb;
                    shtml += '<ul class="page-breadcrumb breadcrumb">';

                    if (ctrl.toolbarbutton != undefined) {
                        shtml += '<li class="btn-group">'
                                + '<div class="clearfix">';



                        rendercontrol(ctrl.toolbarbutton);


                        shtml += '</li>';
                    }

                    shtml += '<li>'
                           + '<i class="fa fa-home"></i>'
                           + '<a href="' + self.getbaseurl() + '">'
                           + 'Home'
                           + '</a>'
                           + '<i class="fa fa-angle-right"></i>'
                           + '</li>';




                    shtml += '</ul>';

                }



                //  shtml += '</div>'
                //+ '</div>';
            }



        }

        var renderdaterange = function (rng) {
            shtml += '<label class="' + (rng.clslabel !== undefined ? rng.clslabel : 'col-md-2') + ' control-label">Date Range</label>'
                    + '<div class="col-md-4">'
                    + '<div class="input-group input-large date-picker input-daterange"  data-date-format="dd-M-yyyy">'
                    + '<input type="text" id="'+rng.name+'_from" class="form-control" name="'+rng.name+'_from">'
                    + '<span class="input-group-addon">'
                    + (rng.btwtext==undefined?'to': rng.btwtext)
                    + '</span>'
                    + '<input type="text" id="'+rng.name+'_to" class="form-control" name="'+rng.name+'_to">'
                    + '</div>';

            if(rng.helptext!=undefined){
                shtml+= '<span class="help-block">'
                    + rng.helptext
                    + '</span>';
            }

            shtml+= '</div>';
        }

        var renderdatepickeronly = function (dtp) {

            shtml+= '<div class="input-group input-medium date date-picker" '
            + (dtp.initdate != undefined ? 'data-date="' + dtp.initdate + '"' : '')
            + ' data-date-format="dd-mm-yyyy" data-date-viewmode="years">'
            + '<input type="text" class="form-control" readonly>'
            + '<span class="input-group-btn">'
            + '<button class="btn default" type="button"><i class="fa fa-calendar"></i></button>'
            + '</span>'
            + '</div>';
        }


        var renderdatepicker = function (dtp) {
            shtml += ' <label class="control-label col-md-2">' + dtp.label + '</label>'
                    + '<div class="' + (dtp.cls == undefined ? dtp.cls : 'col-md-2') + '">';

            renderdatepickeronly(dtp);
     

            if (dtp.helptext != undefined) {
                shtml += '<span class="help-block">'
                        + dtp.helptext
                        + '</span>';
            }

            shtml+= '</div>';
        }


        var renderdropdownonly = function (ddl) {
            shtml +=  '<select id="' + ddl.name + '" '
                    + (ddl.required ? 'required="true" ' : ' ')
                    + 'class="bs-select form-control '+(ddl.ddlcls?ddl.ddlcls:'')+'" name="' + ddl.name + '">';

            if (ddl.unblank == undefined || !ddl.unblank)
                shtml += '<option value="" >' + (ddl.dfltText == undefined ? '-- SELECT ALL --' : ddl.dfltText) + '</option>';

            if (ddl.items != undefined) {
                $.each(ddl.items, function (k, v) {
                    shtml += '<option value="' + k + '">' + v + '</option>';
                });
            }


            shtml += '</select>';

        }

        var renderdropdown = function (ddl) {
            shtml += '<label class="' + (ddl.clslabel !== undefined ? ddl.clslabel : 'col-md-2') + ' control-label">' + ddl.title 
                    +(ddl.required ? '\n<span class="required">*</span>' : '')
                    +'</label>'
                    + '<div class="' + ddl.cls + '">';
            renderdropdownonly(ddl);
		
            if (ddl.helptext != undefined)
                shtml += '<span class="help-block">' + ddl.helptext + '</span>';
            shtml+= '</div>';
        }

        var renderformgroup = function (fg) {
            
            var sid = fg.name || "frmgrp"+ ctrfg;
            shtml += '\n<div ' + (fg.name == undefined ? 'id="frmgrp' + ctrfg + '"' : 'id="' + fg.name + '"') + ' class="form-group">';
            ctrfg++;
            self[sid] = '#' + sid;
            ctrlopt.sid=fg;
            rendercontrol(fg.controls);
            shtml += '\n</div>';

        }

        var renderformgroupbutton = function (fgbtn) {
            shtml += '\n<div class="form-group">'
            + '<label class="col-md-2 control-label">'
                        + '</label>'
                           + '<div class="col-md-10">';
            rendercontrol(fgbtn.controls);
            shtml += '\n</div>';
            shtml += '\n</div>';
        }

        var renderlookupinputbutton=function(lkp)
        {
            var tx = '';
            tx+= '\n<div class="input-group">'
               + '<input id="' + lkp.name + '" '
                + (lkp.disabled ? 'disabled="" ' : ' ')
                + (lkp.readonly ? 'readonly="" ' : ' ')
                + 'name="' + lkp.name + '" type="' + (lkp.ispassword ? 'password' : 'text') + '" class="form-control" placeholder="' + lkp.placeholder + '" >'
                + '<span class="input-group-btn">';


            tx += '\n<a href="#' + lkp.modal + '" data-toggle="modal" id="btnmdl_' + lkp.name + '" class="btn ' + (lkp.size === undefined ? '' : val.size) + ' ' + (lkp.btncolor != undefined ? lkp.btncolor : "blue") + '">'
                           + (lkp.btntext != undefined ? lkp.btntext : "") + '\n<i class="fa fa-' + (lkp.btnicon != undefined ? lkp.btnicon : "search") + '"></i>'
                           + '</a>';

          

            return tx;
        }
        var renderlookup = function (lkp) {
            shtml += '\n<label class="' + (lkp.clslabel !== undefined ? lkp.clslabel : 'col-md-2') + ' control-label">'
                + lkp.label
                + (lkp.required ? '\n<span class="required">*</span>' : '')
                + '\n</label>'
                + '\n<div class="' + lkp.cls + '">'
               
            shtml += renderlookupinputbutton(lkp);
            btnevent.push({ name: '#btnmdl_' + lkp.name, cb: lkp.callback });
            //    renderbutton({
            //        name: "btn_" + lkp.name,
            //        text: (lkp.btntext != undefined ? lkp.btntext : ""),
            //        icon: (lkp.btnicon!=undefined?lkp.btnicon:"search"),
            //        color: (lkp.btncolor != undefined ? lkp.btncolor : "blue"),
            //        onClick: (lkp.callback!=undefined?lkp.callback:'')
            //}); 
            shtml += '\n</span>'
               + '\n</div>';
            shtml += '</div>';
        }


    
        var renderinputtextbox = function (txt) {
            shtml += renderinputtext(txt);
        }
        var renderinputtext = function (txt,useid) {
            return '<input id="' + txt.name + '" '
                  + (txt.minlength != undefined ? 'minlength="' + txt.minlength + '" ' : ' ')
                  + (txt.equalTo != undefined ? 'equalTo="#' + txt.equalTo + '" ' : ' ')
                  + (txt.email != undefined ? 'email="' + txt.email + '" ' : ' ')
                  + (txt.required ? 'required="' + txt.required + '" ' : ' ')
                  + (txt.mustyanu ? 'mustyanu="true" ' : ' ')
                  + (txt.digits ? 'digits="' + txt.digits + '"' : '')
                  + (txt.number ? 'number="' + txt.number + '"' : '')
                  + (txt.disabled ? 'disabled="" ' : ' ')
                  + (txt.readonly ? 'readonly="" ' : ' ')
                  + (txt.maxlength ? 'maxlength="' + txt.maxlength + '" ' : ' ')

                  + 'name="' + (txt.groupname != undefined ? txt.name : txt.name) + '" '
                  + ' type="' + (txt.ispassword ? 'password' : 'text')
                  + '" class="form-control ' + (txt.txtcls ? ' ' + txt.txtcls : '') + '" placeholder="'
                  + txt.placeholder + '" >';
        }

        var rendermultiinput = function (txt)
        {
            shtml += '\n<label class="multicntrl ' + (txt.clslabel !== undefined ? txt.clslabel : 'col-md-2') + ' control-label">'
                 + (txt.label?txt.label:'')
                 + (txt.required ? '\n<span class="required">*</span>' : '')
                 + '\n</label>'
                 + '<div class="multicntrl form-inline ' + txt.cls + '">';

            //$.each(txt.items, function (k,v) {
            //    shtml += '\n'+renderinputtext(v);
            //});
            $.each(txt.items, function (k, v) {
                v.groupname = txt.name;
            });
            rendercontrol(txt.items);


            //if (txt.helptext != undefined)
            //shtml += '<span class="multicntrl help-block" for="' + txt.name + '">' + '</span>';

            shtml += '</div>';

        }    
   
        var rendertextbox = function (txt) {
            shtml += '\n<label class="' + (txt.clslabel !== undefined ? txt.clslabel : 'col-md-2') + ' control-label">'
                  + (txt.label ?txt.label:'')
                  + (txt.required ? '\n<span class="required">*</span>' : '')
                  + '\n</label>'
                  + '<div class="' + txt.cls + '">'
                  + renderinputtext(txt);             

            if (txt.helptext != undefined)
                shtml += '<span>' + txt.helptext + '</span>';

            shtml += '</div>';
        }

        var rendertextarea = function (txa) {
            shtml += '\n<label class="' + (txa.clslabel !== undefined ? txa.clslabel : 'col-md-2') + ' control-label">'
               + txa.label
               + (txa.required ? '\n<span class="required">*</span>' : '')
               + '\n</label>'
               + '\n<div class="' + txa.cls + '">'
               + '\n<textarea id="' + txa.name + '" name="' + txa.name + '" '
               + (txa.disabled ? 'disabled="" ' : ' ')
               + (txa.readonly ? 'readonly="" ' : ' ')
               + (txa.required ? 'required="' + txa.required + '" ' : ' ')
               + 'class="form-control" rows="3"></textarea>\n';

            if (txa.helptext != undefined)
                shtml += '<span class="help-block">' + txa.helptext + '</span>';

            shtml += '</div>';

        }


        var renderswitch = function (swt) {
            lstswitch.push(swt.name);
            shtml += '\n<label class="' + (swt.clslabel !== undefined ? swt.clslabel : 'col-md-2') + ' control-label">'
                 + swt.label
                 + (swt.required ? '\n<span class="required">*</span>' : '')
                 + '\n</label>'
                 + '<div class="' + swt.cls + '">'
                 + '<input id="' + swt.name + '" name="' + swt.name + '" type="checkbox" data-type="switch" checked="" ';

            if (swt.readonly)
                shtml += 'disabled=""';

            if (swt.labelon != undefined)
                shtml += 'data-on-label="&nbsp;' + swt.labelon + '&nbsp;" ';
            if (swt.labeloff != undefined)
                shtml += 'data-off-label="&nbsp;' + swt.labeloff + '&nbsp;" ';

            shtml += 'class="make-switch">';

            if (swt.helptext != undefined)
                shtml += '<span class="help-block">' + swt.helptext + '</span>';

            shtml += '</div>';

            //event click
            //$('input[name="IsActive"]').on('switch-change', function (event, state) {
            //    console.log(this); // DOM element
            //    console.log(event); // jQuery event
            //    console.log(state.value); // true | false
            //});

            //get
            //$('input[name="IsActive"]').bootstrapSwitch('state')
            //set
            //$('input[name="IsActive"]').bootstrapSwitch('setState',0)


        }

        var renderbtndropdown = function (btn) {
            shtml += '\n<li>'
                            + '\n<a href="#">'
                        + '\n' + btn.text
                    + '\n</a>'
                + '\n</li>'
        }

        var rendergrid = function (grd) {
            ctrlopt[grd.name] = grd;
            if (grd.hr)
                shtml += '<hr>';

            shtml += '\n<div id="'+grd.name+'_toolbar'+'" class="table-toolbar">'
                  + '\n<div class="btn-group">'
                   + '\n<div class="clearfix">';
            if (grd.tabletoolbar != undefined) {
                rendercontrol(grd.tabletoolbar);
            }

            shtml += '</div>'
                  + '</div>';
            if (grd.toolbtn != undefined) {
                shtml += '\n<div class="btn-group pull-right">'
                      + '\n<button class="btn ' + (grd.toolbtn.color === 'undefined' ? '' : grd.toolbtn.color) + ' dropdown-toggle" data-toggle="dropdown">' + grd.toolbtn.text + ' <i class="fa fa-angle-down"></i>'
                      + '\n</button>'
                + '\n<ul class="dropdown-menu pull-right">';
                rendercontrol(grd.toolbtn.items);

                shtml += '\n</ul>'
            + '\n</div>';

            }
            shtml += '\n</div>'

            shtml += '\n<table class="table table-striped table-bordered table-hover" id="' + grd.name + '">'
                  + '\n<thead>'
                  + '\n<tr>'
                  + '\n</tr>'
                  + '\n</thead>'
                  + '\n<tbody></tbody>'
                  + '\n</table>';
            
            if (grd.additembtn ) {
                console.log('masukk');
                shtml += '<div class="form-group"><div class="col-md-10">'
                        + '<a class="btn green" style="display:none" id="btn_' + grd.name + '_additem" >Add Item'
                        + '\n<i class="fa fa-plus"></i></a>'
                        + '</div>';
                        
            }
        }

        var getportlettoolbar = function (itm) {

            var ctarrtmp = {
                collapse: '<a href="javascript:;" class="collapse"></a>',
                config: '<a href="#portlet-config" data-toggle="modal" class="config"></a>',
                reload: '<a href="javascript:;" class="reload"></a>',
                remove: '<a href="javascript:;" class="remove"></a>'
            };

            var cttemp = '<div class="tools">';


            if (itm === 'all')
                return "";
            else {
                cttemp = '<div class="tools">';
                $.each(ctarrtmp, function (key, val) {

                    if (itm === 'undefined') {
                        cttemp += val;
                    }
                    else {

                        if ($.inArray(key, itm) < 0)
                            cttemp += val;
                    }
                });
            }
            return cttemp += '</div>';
        }

        var renderportlet = function (prtlt) {
            if (prtlt.mustvalid)
                mustvalid += ",#frm_" + prtlt.name;

            shtml += '\n'
                  + '<div class="portlet box ' + prtlt.color + ' ' + (prtlt.hidden ? 'hide' : '') + '" id="' + prtlt.name + '">'
                    + '<div class="portlet-title">'
                        + '<div class="caption">'
                            + '<i class="fa fa-' + prtlt.icon + '"></i>' + prtlt.title
                        + '</div>'
                        + getportlettoolbar(prtlt.hidetool)
                    + '</div>'
                    + '<div class="portlet-body form">'
                         + '<' + (prtlt.notform ? 'div' : 'form') + ' class="form-horizontal" id="frm_' + prtlt.name + '" role="form">'
                            + '<div class="form-body">';

            rendercontrol(prtlt.body);


            shtml += '</div>'
            //action 					
                  + '</' + (prtlt.notform ? 'div' : 'form') + '>'
           + '</div>'
           + '</div>';
        }

        var renderhhh = function (h) {
            shtml += '\n<h3>' + h.text + '</h3>';
            if (h.hr)
                shtml += '\n<hr>';

        }
        var rendertext = function (t) {
            shtml += t.text;
        }

        var renderrow = function (rw) {
            shtml += '\n<div class="row">'
                            + '\n<div class="col-md-12">';


            rendercontrol(rw.controls);
            shtml += '\n</div>'
                     + '\n</div>';
        }

   


        this.PopulateCombo=function(cmb) {
            if (cmb.uri == undefined)
                cmb.uri = 'api/APIcom/lookupcombo/' + cmb.nmspc;

            $.ajax({
                type: "POST",
                url: baseurl + cmb.uri,
                async:(cmb.async!=undefined?cmb.async:true),
                data:cmb.params,
                dataType: "json",
                beforeSend: function () {
                    $("#" + cmb.name).addClass("spinner");
                },
                complete: function () {
                    $("#" + cmb.name).removeClass("spinner");
                },
                success: function (rslt) {                
                    $("#" + cmb.name + " option:not(:first)").remove()
                    $.each(rslt, function (k, v) {
                        var o = new Option(v.text, v.value);                    
                        $(o).html(v.text);
                        $("#" + cmb.name).append(o);
                    });
              
                }
            });
        }
        this.populatedata = function (lkp,slctr) {
            $.ajax({
                type: "POST",
                url: this.getbaseurl() + lkp.url,
                dataType: "json",
                success: function (rslt) {
                    $.each(rslt, function (key, value) {                      
                        var ctrl = $("[name=" + key + "]");
                        var type = ctrl.data("type");
                        $(ctrl).removeClass("error");

                        if (type === undefined) {
                            if($(slctr + " #" + key).hasClass("mstarea"))
                            {
                                if(key.toLowerCase()=='province')
                                {
                                    if($(slctr+" #City").length>0)
                                    {                                        
                                        self.PopulateCombo({ uri: 'api/APIcom/comboarea/k/' + value, name: "City", async: false });
                                    }
                                }
                                else if(key.toLowerCase()=='city')
                                {
                                    if($(slctr+" #SubDistrict").length>0)
                                    {                                       
                                        self.PopulateCombo({ uri: 'api/APIcom/comboarea/c/' + value, name: "SubDistrict", async: false });
                                    }
                                }
                            }                            
                            
                            $(slctr + " #" + key).val(value);
                            
                        }
                        else {                            
                            if (type === "switch") {                                
                                $(slctr + " [name='" + key + "']").bootstrapSwitch('state', (value == 0 ? false : true));
                            }
                            else if (type === "datepicker" || type === "date") {
                                value = (value) ? moment(value).format(SimDms.dateFormat) : undefined;
                                $(slctr + "[name=\"" + key + "\"]").val(value);
                            }
                            else {
                                $(slctr + " #" + key).val(value);
                            }

                            
                        }
                        //}

                        //if (callback && typeof (callback) === "function") {
                        //    callback(result);
                        //}
                    

                    });

                    //if(cb
                }
            });
        }

        this.getSelectedGridRow = function (gridid) {
            var ar = [];
            var c = 0;
            $.each($("#" + gridid).find("input[type='checkbox']:checked"), function (k, v) {
                ar[c] = v.id.substring(3);
                c++;
            });
            return ar;
        };

        this.populate = function (data, selectorContainer) {
            $.each(data, function (key, value) {
                var $ctrl = $("[name=" + key + "]");
                var type = $ctrl.data("type");
                $ctrl.removeClass("error");

                if (type === undefined) {
                    $(selectorContainer + " [name=\"" + key + "\"]").val(value);
                }
                else {
                    if (type === "switch") {
                        value = (value || false);
                        $(selectorContainer + " [name='" + key + "']").bootstrapSwitch('state', value);
                    }
                    if (type === "datepicker" || type === "date") {
                        value = (value) ? moment(value).format(SimDms.dateFormat) : undefined;
                        $(selectorContainer + "[name=\"" + key + "\"]").val(value);
                    }
                }
            });
        }
        
        $.fn.serializeObject = function () {
            var o = {};
            $(this).find('input[type="hidden"], input[type="text"], input[type="password"], input[type="checkbox"]:checked, input[type="radio"]:checked, select, textarea').each(function () {

                if ($(this).attr('type') == 'hidden') { //if checkbox is checked do not take the hidden field
                    var $parent = $(this).parent();
                    var $chb = $parent.find('input[type="checkbox"][name="' + this.name.replace(/\[/g, '\[').replace(/\]/g, '\]') + '"]');
                    if ($chb != null) {
                        if ($chb.prop('checked')) return;
                    }
                }

                if (this.name === null || this.name === undefined || this.name === '') return;
                var elemValue = null;
                if ($(this).is('select')) {                
                    elemValue = $(this).find('option:selected').val();
                }
                else if ($(this).hasClass("number")) {
                    elemValue = this.value.replace(",", "");
                }
                else if ($(this).hasClass("make-switch")) {
             
                    elemValue = $('input[name="' + this.name + '"]').bootstrapSwitch('state');
                }
                else {
                    var type = $(this).data("type") || "";
                    switch (type) {
                        case "int":
                            elemValue = $(this).data("kendoNumericTextBox").value();
                            break;
                        case "decimal":
                            elemValue = $(this).data("kendoNumericTextBox").value();
                            break;
                        case "datepicker":
                            if (this.value.length > 0) {
                                elemValue = moment(this.value, SimDms.dateFormat).format("YYYY-MM-DD");
                            }
                            else {
                                elemValue = undefined;
                            }
                            break;
                        case "kdatepicker":
                            if (this.value.length > 0) {
                                elemValue = moment(this.value, SimDms.dateFormat).format("YYYY-MM-DD");
                            }
                            else {
                                elemValue = undefined;
                            }
                            break;
                        case "datetimepicker":
                            if (this.value.length > 0) {
                                elemValue = moment(this.value, SimDms.dateTimeFormat).format("YYYY-MM-DD HH:mm");
                            }
                            else {
                                elemValue = undefined;
                            }
                            break;
                        case "kdatetimepicker":
                            if (this.value.length > 0) {
                                elemValue = moment(this.value, SimDms.dateTimeFormat).format("YYYY-MM-DD HH:mm");
                            }
                            else {
                                elemValue = undefined;
                            }
                            break;
                        case "kmonthpicker":
                            if (this.value.length > 0) {
                                elemValue = moment(this.value, "MMMM YYYY").format("YYYYMM");
                            }
                            else {
                                elemValue = undefined;
                            }
                            break;
                        default:
                            elemValue = this.value;
                            break;
                    }
                }

                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(elemValue || '');
                } else {
                    o[this.name] = elemValue;
                }
            });
        
            return o;
        }







    }